import { deleteShopCartById, requestShopChartInfo, updateShopCartStatusById } from '@/api'

export default {
  namespaced: true,
  actions: {
    async getShopChartInfo(context) {
      let result = await requestShopChartInfo()
      if (result.code === 200) {
        context.commit('GETSHOPCHARTINFO', result.data)
      }
    },
    async deleteCartById(context, skuId) {
      let result = await deleteShopCartById(skuId)
      if (result.code === 200) {
        return 'ok!'
      } else {
        return Promise.reject(new Error('failed'))
      }
    },
    async updateCartById(context, { skuId, isChecked }) {
      let result = await updateShopCartStatusById(skuId, isChecked)
      if (result.code === 200) {
        return 'ok!'
      } else {
        return Promise.reject(new Error('falied'))
      }
    },
    deleteAllCheckedCartList({ dispatch, getters }) {
      let promiseAll = []
      getters.cartInfoList.cartInfoList.forEach(item => {
        let p = (item.isChecked === 1 ? dispatch('deleteCartById', item.skuId) : '')
        promiseAll.push(p)
      });
      return Promise.all(promiseAll)
    }
  },
  mutations: {
    GETSHOPCHARTINFO(state, val) {
      state.shopChartList = val
    }
  },
  state: {
    shopChartList: []
  },
  getters: {
    cartInfoList(state) {
      return state.shopChartList[0] || {}
    }
  }
}